﻿Public Class Form1
    Private FPath As String
    Private IsClose As Boolean
    Private FQ As New Queue(Of String)
    Private MsgQ As New Queue(Of String)
    Private FDelQ As New Queue(Of String)
    Private ConnStr As String
    Private DControl As New DBOperation
    Private FThABR As Boolean
    Private CSec As Integer = 0
    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        IsClose = True
    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        FPath = Application.StartupPath
        Threading.ThreadPool.SetMaxThreads(10, 10)
        FThABR = True
        MsgQ.Enqueue("初始化")
        Timer1.Interval = 3000
        Timer1.Enabled = True
        Timer1.Start()
        Timer2.Interval = 1000
        Timer2.Enabled = True
        Timer2.Start()
        MsgQ.Enqueue("初始化完成")
        MsgQ.Enqueue(String.Format("当前时间:{0}点", Now.Hour))
    End Sub
    Private Sub Process()
        Try
            MsgQ.Enqueue("处理线程已启动")
            For i As Integer = 0 To FQ.Count - 1
                Dim FAtxt As String = FQ.Dequeue()
                Dim TmpStr As String() = Split(FAtxt, "||", -1, CompareMethod.Text)
                Dim FClientName As String = TmpStr(0)
                Dim FFilePath As String = TmpStr(1)
                Dim sqlstr As String = "select t.CustomerID,t1.MeterNo,t.PE,t.UnitPrice,t.TotalCost,t.PETime,t.PETimes,t.RE,t.ME,t.TotalConsume,t.ST,t.Operator,t1.UserName,t1.Address,t1.Telephone,t1.Area,t1.PhaseWire,t1.MaxLoad,t1.DelayTime,t1.AE from [IC_SDJL] as t left join [IC_USER] as t1 on t.CustomerID=t1.CustomerID"
                Dim ds As New DataSet
                Dim ErrString As String = String.Empty
                ConnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""{0}"";Jet OLEDB:Database Password=19770908;", FFilePath)
                MsgQ.Enqueue("处理文件:" & FFilePath)
                Dim MyConn As New OleDb.OleDbConnection(ConnStr)
                Try
                    MyConn.Open()
                Catch ex As Exception
                    MsgQ.Enqueue(String.Format("打开数据库失败!{0}删除文件{0}{1}", vbCrLf, ex.Message))
                    MyConn.Dispose()
                    MyConn = Nothing
                    FDelQ.Enqueue(FFilePath)
                End Try
                If MyConn Is Nothing Then
                    Continue For
                End If
                If MyConn.State <> ConnectionState.Open Then
                    Continue For
                End If
                '--读取信息
                Dim da As New OleDb.OleDbDataAdapter(sqlstr, MyConn)
                da.Fill(ds)
                '--循环对比
                For j As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    sqlstr = String.Format("select count(*) as a from IC_SDJL where CustomerID='{0}' and PETime='{1}' and TotalCost='{2}' and PETimes='{3}' and FClient='{4}'", ds.Tables(0).Rows(j).Item("CustomerID"), ds.Tables(0).Rows(j).Item("PETime"), ds.Tables(0).Rows(j).Item("TotalCost"), ds.Tables(0).Rows(j).Item("PETimes"), FClientName)
                    Dim ds1 As New DataSet
                    If DControl.QuerySQL(sqlstr, ds1, ErrString) = False Then
                        MsgQ.Enqueue("对比失败!")
                        Return
                    End If
                    If ds1.Tables(0).Rows(0).Item("a") > 0 Then
                        '--已存在
                    Else
                        '--不存在,增加记录
                        sqlstr = String.Format("Insert into IC_SDJL(CustomerID,MeterNo,PE,UnitPrice,TotalCost,PETime,PETimes,RE,ME,Totalconsume,ST,Operator,UserName,Address,Telephone,Area,PhaseWire,MaxLoad,DelayTime,AE,FClient) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}')", ds.Tables(0).Rows(j).Item("CustomerID"), ds.Tables(0).Rows(j).Item("MeterNo"), ds.Tables(0).Rows(j).Item("PE"), ds.Tables(0).Rows(j).Item("UnitPrice"), ds.Tables(0).Rows(j).Item("TotalCost"), ds.Tables(0).Rows(j).Item("PETime"), ds.Tables(0).Rows(j).Item("PETimes"), ds.Tables(0).Rows(j).Item("RE"), ds.Tables(0).Rows(j).Item("ME"), ds.Tables(0).Rows(j).Item("TotalConsume"), ds.Tables(0).Rows(j).Item("ST"), ds.Tables(0).Rows(j).Item("Operator"), ds.Tables(0).Rows(j).Item("UserName"), ds.Tables(0).Rows(j).Item("Address"), ds.Tables(0).Rows(j).Item("Telephone"), ds.Tables(0).Rows(j).Item("Area"), ds.Tables(0).Rows(j).Item("PhaseWire"), ds.Tables(0).Rows(j).Item("MaxLoad"), ds.Tables(0).Rows(j).Item("DelayTime"), ds.Tables(0).Rows(j).Item("AE"), FClientName)
                        If DControl.ExecSQL(sqlstr, ErrString) = False Then
                            MsgQ.Enqueue(String.Format("插入数据失败!{0}{1}", vbCrLf, ErrString))
                        End If

                    End If
                    If IsClose Then
                        Exit Sub
                    End If
                Next
                MyConn.Close()
                MyConn.Dispose()
                MsgQ.Enqueue("删除文件:" & FFilePath)
                FDelQ.Enqueue(FFilePath)
                If IsClose Then
                    Exit Sub
                End If
            Next
            MsgQ.Enqueue("处理线程关闭")
            FThABR = True
        Catch ex As Exception
            MsgQ.Enqueue(String.Format("处理线程退出,原因:{0}", ex.Message))
            FThABR = True
        End Try
    End Sub
    Private Sub GetFiles()
        Try
            MsgQ.Enqueue("监控线程启动")
            MsgQ.Enqueue("删除已处理文件")
            For i As Integer = 0 To FDelQ.Count - 1
                Try
                    Dim Fpath As String = FDelQ.Dequeue()
                    System.IO.File.Delete(Fpath)
                    MsgQ.Enqueue(String.Format("删除文件:{0}成功", Fpath))
                Catch ex As Exception
                    MsgQ.Enqueue(String.Format("删除文件:{0}失败.原因:{1}", FPath, ex.Message))
                End Try
            Next
            Dim TPath As String = String.Empty
            For i As Integer = 1 To 5
                TPath = String.Format("{0}\App_Data\el{1:000}\", FPath, i)
                MsgQ.Enqueue("读取文件列表 " & TPath)
                '--取文件夹信息
                Dim Di As New System.IO.DirectoryInfo(TPath)
                '--取所有MDB文件
                Dim FInfo() As System.IO.FileInfo = Di.GetFiles("*.mdb", IO.SearchOption.TopDirectoryOnly)
                MsgQ.Enqueue(String.Format("找到{0}个文件", FInfo.Length))
                '--加入队列
                For j As Integer = 0 To FInfo.Length - 1
                    FQ.Enqueue(String.Format("el{0:000}||{1}", i, FInfo(j).FullName))
                Next
            Next
            '--启动线程
            FThABR = False
            MsgQ.Enqueue("准备启动处理线程")
            Threading.ThreadPool.QueueUserWorkItem(AddressOf Process)
        Catch ex As Exception
            MsgQ.Enqueue(ex.Message)
            FThABR = True
        End Try
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        If FThABR And (Now.Hour >= 20 Or Now.Hour < 8) Then
            If IsClose Then
                Timer1.Stop()
                Return
            End If
            Threading.ThreadPool.QueueUserWorkItem(AddressOf GetFiles)
        End If
    End Sub

    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
        If MsgQ.Count > 0 Then
            For i As Integer = 0 To MsgQ.Count - 1
                TextBox1.AppendText(MsgQ.Dequeue() & vbCrLf)
            Next
        End If
        CSec += 1
        If CSec >= 3600 Then
            CSec = 0
        End If
    End Sub
End Class
